import java.util.LinkedList;

/**
 * @author LKQ
 * @date 2021/12/24 16:33
 * @description 使用迭代方法
 */
public class Solution2 {
    public static void main(String[] args) {
        TreeNode leaf1 = new TreeNode(1);
        TreeNode leaf3 = new TreeNode(3);
        TreeNode leaf6 = new TreeNode(6);
        TreeNode leaf9 = new TreeNode(9);
        TreeNode leaf2 = new TreeNode(2, leaf1, leaf3);
        TreeNode leaf7 = new TreeNode(7, leaf6, leaf9);
        TreeNode root = new TreeNode(4, leaf2, leaf7);
        Solution2 s = new Solution2();
        s.invertTree(root);
    }
    public TreeNode invertTree(TreeNode root) {
        if(root==null) {
            return null;
        }
        //将二叉树中的节点逐层放入队列中，再迭代处理队列中的元素
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()) {
            //每次都从队列中拿一个节点，并交换这个节点的左右子树
            TreeNode tmp = queue.poll();
            TreeNode left = tmp.left;
            tmp.left = tmp.right;
            tmp.right = left;
            //如果当前节点的左子树不为空，则放入队列等待后续处理
            if(tmp.left!=null) {
                queue.add(tmp.left);
            }
            //如果当前节点的右子树不为空，则放入队列等待后续处理
            if(tmp.right!=null) {
                queue.add(tmp.right);
            }

        }
        //返回处理完的根节点
        return root;
    }

}
